/**
 * 20220303: dynamic importing and loading assets...jordia
 * 20220310：since no longer support [array-input],remove [object->array] converting
 * 20221010: rewrite with typescript.
 */
 import ThreeContainer from 'three-lib/container/three-container';
import {AssetsLoader, AssetInfo} from './assets-loader';

 interface UrlGetter{
    ():any;
 }

 const setAssetsUrl=(getUrl:UrlGetter)=>{
     return new Promise((resolve,reject)=>{
         let url=getUrl();
         resolve(url);
     })
 };
 
 /**
  * load assets
  * @param {ThreeContainer} threeContainer a container to receive and handle loading events 
  * @param {Object} loaderOut an object to store the AssetsLoader instance
  * @param {function} getURL a function to get all assets urls,the value returned could be
  *                   an object:
  *                               {
  *                                   point:import('../../assets/textures/point.png'),
  *                                   lightCube:[ import('../../assets/textures/lightCube/px.png'),...],
  *                               };
  *                   or a class instance:
  *                               new class Assets{
  *                                          model=import('../../assets/models/model.glb');
  *                                          lightCube=[ import('../../assets/textures/lightCube/px.png'),...];
  *                                   };
  *                           
  *                      
  */
 const assetsLoad=async (threeContainer:ThreeContainer,loaderOut:any,getURL:UrlGetter)=>{
 
     let assetsInfo:any;
     await setAssetsUrl(getURL).then((md)=>{
         assetsInfo=md;
     });
     
     for(let key in assetsInfo){
         const info=assetsInfo[key];
         if(Array.isArray(info)){
             for(let j=0;j<info.length;j++){
                 await info[j].then((m:any)=>{info[j]=m.default;});
             }
         }else{
             await info.then((m:any)=>{assetsInfo[key]=m.default;});
         }
     }
     let loader=new AssetsLoader().setTargets(assetsInfo);
     loaderOut.assetsLoader=loader;
     return new Promise((resolve,reject)=>{
         loader.onLoadStart=()=>{
             threeContainer.startLoad();
         };
         loader.onLoading=(info:AssetInfo,prg:number)=>{
             threeContainer.loading("资源"+ info.name +"加载中…",prg);
         };
         loader.onError=(err:any)=>{
             reject();
             threeContainer.loadError("["+err.join(",")+"] 加载错误！");
         };
         loader.onLoaded=()=>{
             resolve(null);
             setTimeout(()=>{
                 threeContainer.loaded();
             },100)
         };
 
         loader.startLoad();
     });
 
 };
 
 
 export default assetsLoad;